package com.suisung.shopsuite.pay.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.wechat.pay.java.core.util.PemUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.PrivateKey;
import java.util.Base64;
import java.util.Locale;

@Slf4j
public class WeChatPayInfo {
    public static final String appid = "wx7f98a7cb1fb8b82e";
    public static final String secret = "d596587de2a2dcc5f2e668f6a71c19ec";

    /** 商户号 */
    public static final String merchantId = "1716304831";
    /** 商户API私钥路径 */
    public static final String privateKeyPath = "/home/apiclient_cert.pem";
    public static final String platformCertPath = "/home/pub_key.pem";
    /** 商户证书序列号 */
    public static final String merchantSerialNumber = "5078EDD41B1D5424790B29563F9F6CF3352EF386";
    /** 商户APIV3密钥 */
    public static final String apiV3key = "Ybkyydsyzhyslyybqqjy9gyytgsjkfcv";


    public static final String ali_oss_bucket_name = "ybkcos-1327491102";
    public static final String ali_oss_secret_id = "AKIDiHdstjMn0zkNp8Ei163nJchZQ6axQsFW";
    public static final String ali_oss_secret_key = "FI1fjbQ2qqz202weFj6Mj4Piu1ypYAYp";
    public static final String ali_oss_endpoint = "cos.ap-shanghai.myqcloud.com";
    public static final String ali_oss_default_dir = "modulithshop";

    public static final int KEY_LENGTH_BYTE = 32;
    public static final int TAG_LENGTH_BIT = 128;

    public static final String tencentSmsSecretId = "AKIDXxDdx77wZ4Ws2ztiPuCH8qNgoleKm15z";
    public static final String tencentSmsSecretKey = "zsZ6c45wZv41rTs33qQmvsc9XlRwEJBp";
    public static final String tencentSmsAppid = "1400997805";
    public static final String tencentSmsSignName = "江苏品地道网络";


    public static Notification decryptToStringNotify(HttpServletRequest request) {
        try (ServletInputStream inputStream = request.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String serialNo = request.getHeader("Wechatpay-Serial");
            String signature = request.getHeader("Wechatpay-Signature");

            // 读取请求体
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            String notify = sb.toString();
            log.info("wechatNotify 微信支付通知原始数据体: {}", notify);
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            PrivateKey privateKey = PemUtil.loadPrivateKeyFromPath(privateKeyPath);
            certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, privateKey)), apiV3key.getBytes());
            Verifier verifier = certificatesManager.getVerifier(merchantId);
            String s = verifier.getSerialNumber().toUpperCase(Locale.ROOT);
            NotificationHandler notificationHandler = new NotificationHandler(verifier, apiV3key.getBytes());
            NotificationRequest notificationRequest = new NotificationRequest.Builder().withSerialNumber(merchantSerialNumber).withNonce(nonce).withTimestamp(timestamp).withSignature(signature).withBody(notify).build();

            Notification parse = notificationHandler.parse(notificationRequest);
            log.info("wechatNotify 支付异步通知解析明文{}", JSON.toJSONString(parse));

            return parse;
        } catch (Exception e) {
            log.error("wechatNotify error 解析付款通知出错：{}", e.getMessage(), e);
            return null;
        }
    }

    public static void main(String[] args) {
//        String ciphertext = "iFnYTbBr26vwP/Yz6HxssheWIqzm90lxIe6Q7GQj/RJEnLjM+ydi6QSidTsk9rgj9Ty6oa1liYWVcyH01lXfWScKcOhkVU0qi1fmrNEWx8tkt+oqLCdf8UqvFK0hbYiJ41HMEW45MUUwoj2NSnR0cDjvBUs8ET1HT6EYNfxIGVERVmoAckL/sfUA+k+Z2a41m9/qx7ClzcM2zHjZKPIybEGboWWVk8f6thb5IxOVwUP4I2dSI6uLMEf+bvFppMdxYGRz6qHlYJA15ZPsl64HvRYNOfa4F11QPIXGOhsoI4HMsAqlTi7qNEvoKzEFanoDWgZ/TCcVjkYhYwDhevfIofnsJd9r5SVabjsLN2UUMUcJi52XoK1CVTEYKr0/4KyJJL+URPJrCqwBIM2TvGcCMHd5b+Mi/NQqyH0Mh0NMk61MezjpGeihvVxBbNw1upQ16qLU6hsxMVD292XKy2lgEz7yvjvIhzfCKnjPOsPpuvcw04cuhmBo9ubN+I2RY03zv4X/EX5sNcDi+gAr8iDFdssfQXrbDLa0So5GPcQvNDO0M1eYkcLdlxlq/MUtQ2ALCm6MTvBndAcczsCFWa1F7u14QQ==";
//        String s = decryptToString("transaction".getBytes(), "W20KaIffJLoR".getBytes(), ciphertext);
//        System.out.println(s);
    }


    // {"mchid":"1716304831","appid":"wx7f98a7cb1fb8b82e","out_trade_no":"JD-20250603-3","transaction_id":"4200002699202506036423044813","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"拼嘻嘻测试商品","success_time":"2025-06-03T19:23:52+08:00","payer":{"openid":"oYgWw7XSV5TYrE7tuEO07b5IWXIM"},
    // "amount":{"total":10,"payer_total":10,"currency":"CNY","payer_currency":"CNY"}}
    public static String decryptToString(HttpServletRequest request) {
        try (ServletInputStream inputStream = request.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

            // 读取请求体
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            String notifyText = sb.toString();
            JSONObject jsonObject = JSONUtil.parseObj(notifyText);
            JSONObject resourceJson = jsonObject.getJSONObject("resource");
            log.info("wechatNotify resourceJson is {}", resourceJson );

            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(apiV3key.getBytes(), "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, resourceJson.getStr("nonce").getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(resourceJson.getStr("associated_data").getBytes());
            return new String(cipher.doFinal(Base64.getDecoder().decode(resourceJson.getStr("ciphertext"))), "utf-8");
        } catch (Exception e) {
            log.error("wechatNotify error " + e.getMessage(), e);
            return null;
        }
    }

}
